import axios from 'axios'
import qs from 'qs'
import { Message, MessageBox } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

// create an axios instance
// use service(option) to send a request, the option is config of the request,
// note that the option will overwrite the default config which set while axios.create()
const service = axios.create({
  // baseURL: 'http://www.bufantec.com', // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (config.method.toLowerCase() !== 'get') {
      // 如果是 post 修改 content-type
      config.headers = { 'content-type': 'application/x-www-form-urlencoded' }

      // post 数据应该放到 data 中
      if (config.data) {
        // 利用 qs 对数据进行序列化处理
        // user: {name: '张三',age: 30} => user[name]='张三' / user.name='张三'
        config.data = qs.stringify(config.data, { allowDots: true })
      }
    }

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['bufan-Token'] = getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data

    // 5001: Illegal token; 5002: error token
    if (res.tokenCode === '5001' || res.tokenCode === '5002') {
      // to re-login
      MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
        confirmButtonText: 'Re-Login',
        cancelButtonText: 'Cancel',
        type: 'warning'
      }).then(() => {
        store.dispatch('user/resetToken').then(() => {
          location.reload()
        })
      })

      return Promise.reject(new Error(res.message || 'Error').message)
    }

    return res
  }
)

export default service
